
import math
from PIL import Image, ImageDraw, ImageFont
from matplotlib.font_manager import findfont, FontProperties


# 查找SimHei字体的具体路径

def hexagon_points(side_length, center):
    """计算六边形顶点的坐标"""
    points = []
    for i in range(6):
        angle_deg = 60 * i + 30
        angle_rad = math.pi / 180 * angle_deg
        points.append((center[0] + side_length * math.cos(angle_rad),
                       center[1] + side_length * math.sin(angle_rad)))
    return points

def create_hexagon_with_background(side_length, background_image_path, text, font_path):
    """创建一个带有背景和文字的六边形图像"""
    # 加载并调整背景图像大小
    background_image = Image.open(background_image_path).resize((side_length * 2, side_length * 2))
    
    # 创建六边形形状
    hex_image = Image.new('RGBA', (side_length * 2, side_length * 2), (0, 0, 0, 0))
    draw = ImageDraw.Draw(hex_image)
    center = (side_length, side_length)
    points = hexagon_points(side_length, center)
    draw.polygon(points, fill=(255, 255, 255, 255))
    
    # 将背景图像粘贴到六边形形状中
    hex_image.paste(background_image, mask=hex_image)
    
    # 添加文字
    draw = ImageDraw.Draw(hex_image)
    font_path = findfont(FontProperties(family=['SimHei']))
    font = ImageFont.truetype(font_path, 32)  # 使用支持中文的字体文件
    
    # 使用textbbox代替textsize
    # textbbox返回的四元组格式为(left, top, right, bottom)
    text_bbox = draw.textbbox((0, 0), text, font=font)
    text_width = text_bbox[2] - text_bbox[0]
    text_height = text_bbox[3] - text_bbox[1]

    # 计算文本位置，使其居中
    position = ((background_image.width - text_width) / 2, (background_image.height - text_height) / 2)

    # 在图像上添加文本
    draw.text(position, text, fill="white", font=font)
    
    return hex_image

# 示例使用
side_length = 100  # 六边形边长
background_image_path = 'input.png'  # 背景图像路径
text = "你好！"  # 要添加的文字
font_path = 'SimHei.ttf'  # 指定包含中文字符的字体文件路径

hexagon_image = create_hexagon_with_background(side_length, background_image_path, text, font_path)
hexagon_image.save('hexagon_output.png')  # 保存结果图像
